﻿CREATE PROCEDURE dbo.s_MovePages_Ex
	(
		@ApplID int,
		@ImageTypeID_From int,
		@PageNumbers varchar(1024) = '',
		@ImageTypeID_To int,
		@PageNumber_After int
	)
AS
BEGIN TRAN

--RAISERROR('PageNumber_After:%d',16,1,@PageNumber_After) RETURN

DECLARE @PIDs TABLE(PageID int)
INSERT INTO @PIDs SELECT PageID FROM GetPageNumbers(@ApplID,@ImageTypeID_From,@PageNumbers)

DECLARE @PageToMoveID int,@PageAfterID int
SELECT @PageAfterID = PageID FROM GetPageNumbers(@ApplID,@ImageTypeID_To,@PageNumber_After)

WHILE 1 = 1 BEGIN
	SELECT TOP 1 @PageToMoveID = PageID FROM @PIDs

	EXEC s_MovePage_Ex	@ApplID,@PageToMoveID,@ImageTypeID_To,@PageAfterID
	PRINT dbo.sprintf3('@ApplID:$0,@PageToMoveID:$1,@ImageTypeID_To:$2,@PageAfterID:$3',@ApplID,@PageToMoveID,@ImageTypeID_To,@PageAfterID)

	IF (SELECT COUNT(*) FROM @PIDs) = 1 BREAK
	
	SET @PageAfterID = @PageToMoveID

	DELETE FROM @PIDs WHERE PageID = @PageTomoveID
END

COMMIT TRAN
